class Cart
  
  attr_reader :product_items, :meal_items

  def initialize(cart_data)
    @cart_data = cart_data
    
    @product_items = @cart_data[:product_ids].uniq.collect do |id|
      begin
        product = Product.find(id)
        quantity = @cart_data[:product_ids].reject{|pid| pid!=id}.size
        CartItem.new(product, quantity)
      rescue
        @cart_data[:product_ids].delete(id)
        nil
      end
    end.compact
    
    @meal_items = @cart_data[:meal_ids].uniq.collect do |id|
      begin
        meal = Meal.find(id)
        quantity = @cart_data[:meal_ids].reject{|mid| mid!=id}.size
        CartItem.new(meal,  quantity)
      rescue
        @cart_data[:meal_ids].delete(id)
        nil
      end
    end.compact
  end
  
  def add_product(product)
    @cart_data[:product_ids] << product.id
  end
  
  def remove_product(product)
    @cart_data[:product_ids].delete_at(@cart_data[:product_ids].index(product.id))
  end
  
  def add_meal(meal)
    @cart_data[:meal_ids] << meal.id
  end
  
  def remove_meal(meal)
    @cart_data[:meal_ids].delete_at(@cart_data[:meal_ids].index(meal.id))
  end
  
  def price
    total = product_items.inject(0) do |sum, p|
      sum += p.price
    end
    total = meal_items.inject(total) do |sum, m|
      sum += m.price
    end
    
    total
  end
  
  def items_count
    total = product_items.inject(0) do |sum, p|
      sum += p.quantity
    end
    total = meal_items.inject(total) do |sum, m|
      sum += m.quantity
    end
    
    total
  end
  
  def empty?
    meal_items.empty? && product_items.empty?
  end
end
